package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.dao.MenuDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.pojo.Menu;
import com.itheima.service.MenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 菜单服务类
 */
@Service(interfaceClass = MenuService.class)
@Transactional
public class MenuServiceImpl implements MenuService {

    @Autowired
    private MenuDao menuDao;    //菜单数据类对象


    //查询所有菜单
    public List<Menu> findAll() {
        return menuDao.findAll();
    }

    //分页查询菜单
    public PageResult findPage(QueryPageBean queryPageBean) {
        Integer currentPage = queryPageBean.getCurrentPage();
        Integer pageSize = queryPageBean.getPageSize();
        String queryString = queryPageBean.getQueryString();
        PageHelper.startPage(currentPage,pageSize);
        //条件查询出所有的一级菜单
        Page<Menu> all = menuDao.findByCondition(queryString);
        for (Menu menu : all) {
            //根据父菜单的id查询出关联的二级子菜单
            List<Menu> children = menuDao.findChildrenByParentId(menu.getId());
            //将查询出来的子菜单设置进父菜单对象的children属性中
            menu.setChildren(children);
        }
        long total = all.getTotal();
        List result = all.getResult();
        return new PageResult(total,result);
    }

    //新增菜单
    public void add(Menu menu) {
        menuDao.add(menu);
    }

    //根据id查询菜单
    public Menu findById(Integer id) {
        return menuDao.findById(id);
    }

    //编辑菜单
    public void edit(Menu menu) {
        menuDao.edit(menu);
    }

    //删除菜单
    public void delete(Integer id) {
        //先删除菜单和角色的关联关系
        menuDao.deleteMenuAndRole(id);
        //删除菜单
        menuDao.delete(id);
    }


}
